//
//  XZSegmentBar.m
//  XZSegmentDemo
//
//  Created by Dreamer on 2018/1/28.
//  Copyright © 2018年 dreamer. All rights reserved.
//

#import "XZSegmentBar.h"

#import "UIView+XZFrame.h"

#import "XZSegmentLabel.h"

#define XZScreenW [UIScreen mainScreen].bounds.size.width
#define XZScreenH [UIScreen mainScreen].bounds.size.height

@interface XZSegmentBar()

/** 标题滚动视图 */
@property (nonatomic, weak) UIScrollView *titleScrollView;

/** 下标视图 */
@property (nonatomic, weak) UIView *underLine;

/** 标题遮盖视图 */
@property (nonatomic, weak) UIView *coverView;

/** 所有标题数组 */
@property (nonatomic, strong) NSMutableArray *titleArray;

/** 所有标题数组 */
@property (nonatomic, strong) NSMutableArray *titleLabels;

/** 所有标题宽度数组 */
@property (nonatomic, strong) NSMutableArray *titleWidths;

@property (nonatomic, strong) XZSegmentConfig *segmentConfig;

/**  开始RGB */
@property (nonatomic, assign) CGFloat startR;

@property (nonatomic, assign) CGFloat startG;

@property (nonatomic, assign) CGFloat startB;

/**  结束RGB */
@property (nonatomic, assign) CGFloat endR;

@property (nonatomic, assign) CGFloat endG;

@property (nonatomic, assign) CGFloat endB;

@end

@implementation XZSegmentBar

- (void)setUpSegmentTitleArr:(NSMutableArray<NSString *> *)titleArr configBlock:(void(^)(XZSegmentConfig *))configBlock {
    self.titleArray = titleArr;
    
    XZSegmentConfig *segmentCongfig = [XZSegmentConfig defaultConfig];
    
    if (configBlock) {
        configBlock(segmentCongfig);
    }
    
    self.segmentConfig = segmentCongfig;
    
    [self setUpTitleWidths];
    [self setUpTitleLabels];
    [self setUpRGB];
}

- (void)setUpTitleWidths {
    CGFloat totalWidth = 0;
    
    // 计算所有标题的宽度
    for (NSString *title in self.titleArray) {
        
        CGRect titleBounds = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.segmentConfig.segNormalFont} context:nil];
        
        CGFloat width = titleBounds.size.width;
        
        [self.titleWidths addObject:@(width)];
        
        totalWidth += width;
    }
}

- (void)setUpTitleLabels {
    NSUInteger count = self.titleArray.count;
    
    CGFloat labelW = 0;
    CGFloat labelH = self.height - self.segmentConfig.underLineH;
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    
    for (NSInteger i = 0; i < count; i++) {
        XZSegmentLabel *label = [[XZSegmentLabel alloc] init];
        
        label.tag = i;
        label.textColor = self.segmentConfig.segNormalColor;
        label.font = self.segmentConfig.segNormalFont;
        
        labelW = [self.titleWidths[i] floatValue];
        
        UILabel *lastLabel = [self.titleLabels lastObject];
        
        labelX = self.segmentConfig.segTitleMargin + CGRectGetMaxX(lastLabel.frame);
        
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleClick:)];
        [label addGestureRecognizer:tap];
        
        [self.titleLabels addObject:label];
        
        [self.titleScrollView addSubview:label];
    }
    
    UILabel *lastLabel = self.titleLabels.lastObject;
    self.titleScrollView.contentSize = CGSizeMake(self.segmentConfig.segTitleMargin + CGRectGetMaxX(lastLabel.frame), 0);
}

- (void)setUpRGB{
    if (self.segmentConfig.isShowTitleGradient) {
        CGFloat startComponents[3];
        [self getRGBComponents:startComponents forColor:self.segmentConfig.segNormalColor];
        self.startR = startComponents[0];
        self.startG = startComponents[1];
        self.startB = startComponents[2];
        
        CGFloat endComponents[3];
        [self getRGBComponents:endComponents forColor:self.segmentConfig.segSelectedColor];
        self.endR = startComponents[0];
        self.endG = startComponents[1];
        self.endB = startComponents[2];
    }
}

- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char resultingPixel[4];
    CGContextRef context = CGBitmapContextCreate(&resultingPixel, 1, 1, 8, 4, rgbColorSpace, 1);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorSpace);
    for (int component = 0; component < 3; component++) {
        components[component] = resultingPixel[component] / 255.0f;
    }
}

- (void)titleClick:(UITapGestureRecognizer *)tap {
    XZSegmentLabel *label = (XZSegmentLabel *)tap.view;
    
    _selectIndex = label.tag;
    
    if ([self.delegate respondsToSelector:@selector(segmentBarDidSelectIndex:)]) {
        [self.delegate segmentBarDidSelectIndex:_selectIndex];
    }
    
    [self selectLabel:label];
}

- (void)selectLabel:(XZSegmentLabel *)label {
    
    
    if (self.segmentConfig.isShowUnderLine) {
        
    }
    if (self.segmentConfig.isShowTitleScale) {
        
    }
    if (self.segmentConfig.isShowTitleCover) {
        
    }
    if (self.segmentConfig.isShowTitleGradient) {
        
    }
}

- (void)updateSegmentBarItemWithScrollOffset:(CGFloat)scrollOffset {
    NSInteger leftIndex = scrollOffset / XZScreenW;
    XZSegmentLabel *leftLabel = nil;
    if (leftIndex > 0) {
        leftLabel = self.titleLabels[leftIndex];
    }
    
    NSInteger rightIndex = leftIndex + 1;
    XZSegmentLabel *rightLabel = nil;
    if (rightIndex < self.titleLabels.count) {
        rightLabel = self.titleLabels[rightIndex];
    }
    
    if (self.segmentConfig.isShowTitleScale) {
        [self updateTitleScaleOffset:scrollOffset leftLabel:leftLabel rightLabel:rightLabel];
    }
    if (self.segmentConfig.isShowUnderLine) {
        [self updateUnderLineOffset:scrollOffset leftLabel:leftLabel rightLabel:rightLabel];
    }
    if (self.segmentConfig.isShowTitleCover) {
        [self updateTitleCoverOffset:scrollOffset leftLabel:leftLabel rightLabel:rightLabel];
    }
    if (self.segmentConfig.isShowTitleGradient) {
        [self updateTitleGradientOffset:scrollOffset leftLabel:leftLabel rightLabel:rightLabel];
    }
}

- (void)updateTitleScaleOffset:(CGFloat)offset leftLabel:(UILabel *)leftLabel rightLabel:(UILabel *)rightLabel {
    if (leftLabel == nil || rightLabel == nil) return;
    
    CGFloat rightSacle = offset / XZScreenW - leftLabel.tag;
    CGFloat leftScale = 1 - rightSacle;
    
    CGFloat scaleTransform = self.segmentConfig.segSelectedFont.pointSize / self.segmentConfig.segNormalFont.pointSize;
    
    leftLabel.transform = CGAffineTransformMakeScale(leftScale * scaleTransform + 1, leftScale * scaleTransform + 1);
    rightLabel.transform = CGAffineTransformMakeScale(rightSacle * scaleTransform + 1, rightSacle * scaleTransform + 1);
}

- (void)updateUnderLineOffset:(CGFloat)offset leftLabel:(UILabel *)leftLabel rightLabel:(UILabel *)rightLabel {
    if (leftLabel == nil || rightLabel == nil) return;
    
    CGFloat centerDelta = rightLabel.centerX - leftLabel.centerX;
    CGFloat underLineTransformX = (offset / XZScreenW - leftLabel.tag) * centerDelta;
    self.underLine.centerX = rightLabel.centerX + underLineTransformX;
    
    CGFloat widthDelta = [self.titleWidths[leftLabel.tag] floatValue] - [self.titleWidths[rightLabel.tag] floatValue];
    CGFloat widthTransform = (offset / XZScreenW - leftLabel.tag) * widthDelta;
    self.underLine.width = rightLabel.width + widthTransform;
}

- (void)updateTitleCoverOffset:(CGFloat)offset leftLabel:(UILabel *)leftLabel rightLabel:(UILabel *)rightLabel {
    if (leftLabel == nil || rightLabel == nil) return;
    
    CGFloat centerDelta = rightLabel.centerX - leftLabel.centerX;
    CGFloat underLineTransformX = (offset / XZScreenW - leftLabel.tag) * centerDelta;
    self.coverView.centerX = rightLabel.centerX + underLineTransformX;
}

- (void)updateTitleGradientOffset:(CGFloat)offset leftLabel:(UILabel *)leftLabel rightLabel:(UILabel *)rightLabel {
    if (leftLabel == nil || rightLabel == nil) return;
    
    CGFloat rightSacle = offset / XZScreenW - leftLabel.tag;
    CGFloat leftScale = 1 - rightSacle;
    
    CGFloat r = self.endR - self.startR;
    CGFloat g = self.endG - self.startG;
    CGFloat b = self.endB - self.startB;
    
    leftLabel.textColor = [UIColor colorWithRed:r * rightSacle green:g * rightSacle blue:b * rightSacle alpha:1];
    rightLabel.textColor = [UIColor colorWithRed:r * rightSacle green:g * rightSacle blue:b * rightSacle alpha:1];
}

#pragma mark - set
- (void)setSelectIndex:(NSInteger)selectIndex {
    _selectIndex = selectIndex;
    
    if (selectIndex > 0 && selectIndex < self.titleLabels.count) {
        UILabel *label  = self.titleLabels[selectIndex];
        [self titleClick:[label.gestureRecognizers firstObject]];
    }
}

#pragma mark - get
- (UIScrollView *)titleScrollView {
    if (!_titleScrollView) {
        UIScrollView *titleScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        titleScrollView.scrollsToTop = NO;
        titleScrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:titleScrollView];
        _titleScrollView = titleScrollView;
    }
    return _titleScrollView;
}

- (UIView *)underLine {
    if (!_underLine) {
        UIView *underLine = [[UIView alloc] init];
        [self.titleScrollView addSubview:underLine];
        _underLine = underLine;
    }
    return _underLine;
}

- (UIView *)coverView {
    if (!_coverView) {
        UIView *coverView = [[UIView alloc] init];
        [self.titleScrollView insertSubview:coverView atIndex:0];
        _coverView = coverView;
    }
    return _coverView;
}

- (NSMutableArray *)titleLabels {
    if (!_titleLabels) {
        _titleLabels = [NSMutableArray array];
    }
    return _titleLabels;
}

- (NSMutableArray *)titleWidths {
    if (!_titleWidths) {
        _titleWidths = [NSMutableArray array];
    }
    return _titleWidths;
}

@end
